package com.bilibili.bilibili.fragment;


import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bilibili.bilibili.R;
import com.bilibili.bilibili.adapter.RegionAdapter;
import com.bilibili.bilibili.model.RegionTypesInfo;
import com.bilibili.bilibili.utils.GsonUtil;
import com.bilibili.bilibili.utils.LogUtil;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * A simple {@link Fragment} subclass.
 */
public class RegionFragment extends Fragment {


    private View mView;
    private RecyclerView region_fragemnt;

    public RegionFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_region, container, false);
        initView(mView);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String s = readAssetsJson();
        loadData(s);
    }

    private void loadData(String s) {
        RegionTypesInfo regionTypesInfo = GsonUtil.parseJsonToObj(s, new TypeToken<RegionTypesInfo>() {
        });
        LogUtil.i("TAG", regionTypesInfo.toString());
        RegionAdapter regionAdapter = new RegionAdapter(regionTypesInfo.getData(), getActivity());
        region_fragemnt.setAdapter(regionAdapter);
    }
    //加载数据

    /**
     * 读取assets下的json数据
     */
    private String readAssetsJson() {

        AssetManager assetManager = getActivity().getAssets();
        try {
            InputStream is = assetManager.open("region.json");
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder stringBuilder = new StringBuilder();
            String str;
            while ((str = br.readLine()) != null) {
                stringBuilder.append(str);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void initView(View mView) {
        region_fragemnt = (RecyclerView) mView.findViewById(R.id.region_fragemnt);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        region_fragemnt.setLayoutManager(gridLayoutManager);
    }
}
